# -*- coding: utf-8 -*-
"""
TTS引擎
"""

import asyncio
from pathlib import Path

try:
    import edge_tts
except Exception:
    edge_tts = None


class TTSEngine:
    """语音合成引擎"""

    def __init__(self, voice: str = "zh-CN-XiaoxiaoNeural", rate: str = "+0%", pitch: str = "+0Hz"):
        """
        初始化TTS引擎

        Args:
            voice: 声音
            rate: 语速
            pitch: 音调
        """
        self.voice = voice
        self.rate = rate
        self.pitch = pitch

    async def synthesize(self, text: str, output_path: Path) -> None:
        """
        合成语音

        Args:
            text: 要合成的文本
            output_path: 输出文件路径
        """
        if edge_tts is None:
            raise RuntimeError("edge-tts is not installed. Please `pip install edge-tts`.")

        communicate = edge_tts.Communicate(text=text, voice=self.voice, rate=self.rate, pitch=self.pitch)
        await communicate.save(str(output_path))

    def synthesize_sync(self, text: str, output_path: Path) -> None:
        """
        同步合成语音

        Args:
            text: 要合成的文本
            output_path: 输出文件路径
        """
        asyncio.run(self.synthesize(text, output_path))
